/*
 * 标签
 */

import * as React from 'react';
import { connect } from 'react-redux';
import { get } from 'lodash';

import { Divider, Spin, Icon, Tag, Tooltip, Card, message, Popconfirm } from 'antd';
import CustomPagination from 'components/common/CustomPagination';
import CustomModal from 'components/common/CustomModal';
import SearchForm from './SearchForm';
import EditForm from './EditForm';
import AudioPlayer from 'components/common/AudioPlayer';

import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/tag';

import './Index.scss';

import {
  fetchTagList,
  createTag,
  updateTag,
  removeTag,
  toggleTagCheck,
  initSelectedItems,
} from 'actions/tag';

interface TagProps {
  dispatch: (action: any) => any;
  loadingGroup: any;
  tagTotal: number;
  tagList: object[];
  selectedTags: object[];
  doSelect?: boolean;
  selectMax: number;
}

interface TagState {
  editTag: any;
}

class TagList extends React.Component<TagProps, TagState> {
  pageInit: number;
  pageSizeInit: number;
  filters: any;

  static defaultProps: TagProps = {
    dispatch: () => {},
    loadingGroup: {},
    tagTotal: 0,
    tagList: [],
    selectedTags: [],
    doSelect: false,
    selectMax: 0,
  };
  constructor(props: TagProps) {
    super(props);
    this.state = {
      editTag: null,
    };

    this.pageInit = 1;
    this.pageSizeInit = 10;
    this.filters = {
      page: this.pageInit,
      pageSize: this.pageSizeInit,
    };
  }

  componentDidMount() {
    this.handleFetchTagList();
  }

  showModal = (editTag?: any) => {
    this.setState({
      editTag,
    });
  };

  hideModal = () => {
    this.setState({
      editTag: null,
    });
  };

  // 分页回调
  onPageChange = (page: number) => {
    this.handleFetchTagList({ page });
  };

  /**
   * 查询Tag列表
   */
  handleFetchTagList = (params: any = {}, isSearch: boolean = false) => {
    this.filters = { ...this.filters, ...params };
    if (isSearch) {
      this.filters.page = this.pageInit;
    }
    this.props.dispatch(fetchTagList(this.filters));
  };

  handleRemoveTag = (tagId: number) => {
    this.props.dispatch(removeTag(tagId)).then((result: any) => {
      if (result.code) {
        message.error(result.msg || `Tag删除失败[${result.code}]`);
      } else {
        message.success('Tag删除成功');
        this.handleFetchTagList();
      }
    });
  };

  /**
   * 创建或更新标签
   */
  handleEditorSubmit = (data: Record<string, any>) => {
    const { loadingGroup } = this.props;
    const { editTag } = this.state;

    const loadingKey = editTag ? ACTIONS.UPDATE : ACTIONS.CREATE;

    if (isLoading(loadingGroup, loadingKey)) return;

    const action = editTag ? updateTag(editTag.id, data) : createTag(data);

    this.props.dispatch(action).then((result: any) => {
      if (result.code) {
        message.error(result.msg);
      } else {
        const msg = editTag ? '修改成功' : '创建成功';
        message.success(msg);
        this.handleFetchTagList();
        this.hideModal();
      }
    });
  };

  handleCheckChange = (target: any, checked: boolean) => {
    const { dispatch, doSelect, selectMax } = this.props;

    if (doSelect) {
      dispatch(toggleTagCheck(target, checked, selectMax));
    } else {
      this.setState({
        editTag: target,
      });
    }
  };

  render() {
    const { loadingGroup, tagList, tagTotal, selectedTags, doSelect } = this.props;
    const { editTag } = this.state;

    const loadingKey = editTag ? ACTIONS.UPDATE : ACTIONS.CREATE;

    const paginParams = {
      current: this.filters.page,
      pageSize: this.filters.pageSize,
      total: tagTotal,
      onChange: this.onPageChange,
    };

    const modalProps = {
      title: editTag ? (
        <>
          <Icon type="edit" />
          &nbsp;编辑标签
        </>
      ) : (
        <>
          <Icon type="plus" />
          &nbsp;新增标签
        </>
      ),
      visible: editTag !== null,
      onCancel: this.hideModal,
      footer: false,
      width: 800,
    };

    return (
      <div id="tag_content_box">
        <Card bordered={false}>
          <SearchForm handleSearch={this.handleFetchTagList} showModal={this.showModal} />
        </Card>
        <Card style={{ marginTop: 24, minHeight: 120 }}>
          <Spin spinning={isLoading(loadingGroup, ACTIONS.FETCH_LIST)} tip="Loading...">
            {tagList.length > 0 ? (
              tagList.map((tag: any) => {
                const desc = get(tag, 'description', null);
                const title = (
                  <Card title={desc}>
                    <div style={{ alignItems: 'center', display: 'flex' }}>
                      <AudioPlayer isTiny={true} audioUri={get(tag, 'audio.uri', '')} />
                      <Divider type="vertical" key="line" />
                      <img src={get(tag, 'cover.uri', '')} width="100" />
                    </div>
                  </Card>
                );
                return (
                  <Tooltip placement="bottom" title={title} key={tag.id}>
                    <Tag.CheckableTag
                      checked={
                        !!doSelect &&
                        selectedTags.some((item: any, index: number) => {
                          return item.id === tag.id;
                        })
                      }
                      onChange={(checked: boolean) => {
                        this.handleCheckChange(tag, checked);
                      }}
                      key={tag.id}>
                      {tag.enName}
                      &nbsp;&nbsp;
                      <Popconfirm
                        placement="top"
                        title="确认要删除此标签吗？"
                        onConfirm={e => {
                          e.stopPropagation();
                          this.handleRemoveTag(tag.id);
                        }}
                        onCancel={e => {
                          e.stopPropagation();
                        }}
                        okText="确认"
                        cancelText="取消">
                        <Icon
                          type="cross"
                          onClick={e => {
                            e.stopPropagation();
                          }}
                        />
                      </Popconfirm>
                    </Tag.CheckableTag>
                  </Tooltip>
                );
              })
            ) : (
              <p className="loading-placeholder">
                <Icon type="frown-o" />
                &nbsp; 还没有标签哦
              </p>
            )}
          </Spin>
        </Card>
        <CustomPagination {...paginParams} />
        <div className="clear-both" />
        <CustomModal {...modalProps}>
          <EditForm
            loading={isLoading(loadingGroup, loadingKey)}
            editTag={editTag}
            onSubmit={this.handleEditorSubmit}
          />
        </CustomModal>
      </div>
    );
  }
}

function mapStateToProps(state: any) {
  const { loadingGroup } = state;
  const { tagList, tagTotal, selectedTags } = state.tag;

  return {
    loadingGroup,
    tagList,
    tagTotal,
    selectedTags,
  };
}

export default connect(mapStateToProps)(TagList);
